import pymysql as MySQLdb
import requests
import hashlib
import time
import json

o = '%.3f' % (time.time() / 1e3)
e = o.replace('.', '')
i = "23y0ufFl5YxIyGrI8hWRUZmKkvtSjLQA"
a = "123456789abcdefg"
s = "zdww"


def getSignature1():
    s = hashlib.sha256()
    s.update(str(e + i + a + e).encode("utf8"))
    b = s.hexdigest().upper()
    return b


def getSignature2():
    s = hashlib.sha256()
    s.update(str(e + 'fTN2pfuisxTavbTuYVSsNJHetwq5bJvCQkjjtiLM2dCratiA' + e).encode("utf8"))
    b = s.hexdigest().upper()
    return b


s1 = getSignature1()
s2 = getSignature2()

post_dict = {
    'appId': 'NcApplication',
    'key': '3C502C97ABDA40D0A60FBEE50FAAD1DA',
    'nonceHeader': '123456789abcdefg',
    'paasHeader': 'zdww',
    'signatureHeader': s1,
    'timestampHeader': e
}

headers = {
    'Referer': 'http://bmfw.www.gov.cn/',
    'Origin': 'http://bmfw.www.gov.cn',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0',
    'x-wif-nonce': 'QkjjtiLM2dCratiA',
    'x-wif-paasid': 'smt-application',
    'x-wif-signature': s2,
    'x-wif-timestamp': e,
    'Content-Type': 'application/json; charset=utf-8',
}

url = 'http://103.66.32.242:8005/zwfwMovePortal/interface/interfaceJson'


def get_yq_data(db, logger, table={}):
    req = requests.post(url=url, data=json.dumps(post_dict), headers=headers)
    resp = req.text
    res = json.loads(resp)
    print(res['msg'])

    utime = res['data']['end_update_time']
    hcount = res['data']['hcount']
    mcount = res['data']['mcount']
    logger.info("Response Count: %s", utime)
    print(utime)
    print('高风险：' + str(hcount) + '个')
    print('中风险：' + str(mcount) + '个')

    hlist = res['data']['highlist']
    mlist = res['data']['middlelist']

    create_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

    mysql_cursor = db.cursor
    mysql_cursor.execute("SELECT count(*) - 1 AS count FROM " + table['address'] + " WHERE time = %(utime)s;", {'utime': utime})
    cres = mysql_cursor.fetchall()[0]['count']
    print("此刷新时间已有数据：" + str(cres) + '条')

    db.updateDB(
        "update " + table['address'] + " set province = '%s', city = '%s', time = '%s', create_time = '%s' where id = 1;" % (
            hcount, mcount, utime, create_time))
    print("更新ID为1的数据的更新时间：" + utime)

    if cres <= 0:
        print("开始更新风险地区名单")
        for hd in hlist:
            type = hd['type']
            province = hd['province']
            city = hd['city']
            county = hd['county']
            area_name = hd['area_name']
            communitys = json.dumps(hd['communitys'], ensure_ascii=False)
            db.updateDB(
                "insert into " + table['address'] + "(type, province, city, county, area_name, time, communitys, create_time, level) "
                "values (%s, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');"
                % (type, province, city, county, area_name, utime, communitys, create_time, 2))
            print(area_name)

        for md in mlist:
            type = md['type']
            province = md['province']
            city = md['city']
            county = md['county']
            area_name = md['area_name']
            communitys = json.dumps(md['communitys'], ensure_ascii=False)
            db.updateDB(
                "insert into " + table['address'] + "(type, province, city, county, area_name, time, communitys, create_time, level) "
                "values(%s, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');"
                % (type, province, city, county, area_name, utime, communitys, create_time, 1))
            print(area_name)

